<?php


namespace app\backstage\controller;


use app\backstage\facade\SpreadFacade;
use app\backstage\logic\SpreadLogic;
use app\backstage\model\Link;
use app\backstage\model\ManagerRole;
use app\common\classes\BehaviorRedis;
use app\common\model\NovelChapter;
use app\common\model\NovelClass;
use app\common\model\NovelCustom;
use app\common\model\NovelFreq;
use app\common\model\NovelLabel;
use app\common\model\NovelToLabelAccess;
use app\common\model\QuickLink;
use app\common\model\RechargeTemplate;
use think\Controller;
use think\Db;

/**
 * 推广中心
 * Class Spread
 * @package app\backstage\controller
 */
class Spread extends Controller
{

    protected $middleware = [
        'VerifyJwt' => ['except' => []],
        'VerifyPower' => ['except' => ['createLink']],
    ];

    /**
     * 推广书籍
     * @return mixed
     * @Author: whh
     */
    public function novels()
    {
        $id = trim(input('id'));
        $title = input('title');
        $freq_id = input('freq_id');
        $class_id = input('class_id');
        $update_status = input('update_status', '');
        $words_type = input('words_type', 0);
        $scale = input('scale', '');
        $label_id = input('label_id', 0);
        $keyword = input('keyword');

        $page = input('page', 1);
        $limit = input('limit', 10);
        $where = [];
        if ($id != '') {
            $where[] = ['id', '=', $id];
        }
        if ($title != '') {
            $where[] = ['title', '=', $title];
        }
        if ($scale != '') {
            $where[] = ['scale', '=', $scale];
        }
        $freq = null;
        if ($freq_id != '') {
            $where[] = ['freq_id', '=', $freq_id];
            $freq = NovelFreq::get($freq_id);
        }
        if ($freq) {
            $classArr = $freq->sonClass->toArray();
        } else {
            $classArr = NovelClass::all()->toArray();
        }
        /**
         * 切换频道时，该频道无此分类
         */
        if (!in_array($class_id, array_column($classArr, 'id'))) {
            $class_id = '';
        }
        $class = null;
        if ($class_id != '') {
            $where[] = ['class_id', '=', $class_id];
            $class = NovelClass::get($class_id);
        }
        if ($update_status != '') {
            $update_status = intval($update_status);
            if ($update_status === 0) {
                $where[] = ['update_status', 'in', [0, 2]];//对于客户来说，不需要体现弃更这个玩意
            } else {
                $where[] = ['update_status', '=', $update_status];
            }
        }
        switch ($words_type) {
            case 1:
                $where[] = ['number_words', '<=', 300000];
                break;
            case 2:
                $where[] = ['number_words', 'between', [300000, 500000]];
                break;
            case 3:
                $where[] = ['number_words', 'between', [500000, 1000000]];
                break;
            case 4:
                $where[] = ['number_words', 'between', [1000000, 2000000]];
                break;
            case 5:
                $where[] = ['number_words', '>', 2000000];
                break;
            default;
        }
        if ($label_id != 0) {
            $novelIds = NovelToLabelAccess::where('label_id', $label_id)->column('novel_id');
            $where[] = ['id', 'in', $novelIds];
        }
        if ($keyword != '') {
            $where[] = ['id|title', '=', $keyword];
        }
        $res = SpreadFacade::getNovelList($where, $page, $limit);
        $list = $res['list'];
        $count = $res['count'];
        $labels = NovelLabel::all();
        if ($freq) {
            $classArr = $freq->sonClass->toArray();
        } else {
            $classArr = NovelClass::all()->toArray();
        }
        $this->assign('classArr', $classArr);
        $this->assign('freqArr', NovelFreq::all());
        $this->assign('labels', $labels);
        $this->assign('count', $count);
        $this->assign('limit', $limit);
        $this->assign('list', $list);
        $this->assign('page', $page);
        $this->assign('freq', $freq);
        $this->assign('class', $class);
        $this->assign('update_status', $update_status);
        $this->assign('words_type', $words_type);
        $this->assign('label_id', $label_id);
        $this->assign('keyword', $keyword);
        $this->assign('scale', $scale);
        $this->assign('roleAlias', request()->_role->alias);
        $freq = NovelFreq::all();
        foreach ($freq as $k => $v) {
            $v->sonClass;
        }
        $redis = new BehaviorRedis();
        $readNovelCount = $redis->readingNovels();
        $readUserCount = $redis->readingUsersCount();
        $this->assign('freqJson', json_encode($freq));
        $this->assign('readNovelCount', $readNovelCount);
        $this->assign('readUserCount', $readUserCount);
        //return $this->fetch();
        $this->assign('role_name', request()->_role->alias);
        return $this->fetch('new_novels');
    }

    /**
     * 自定义收费配置页面
     * @return mixed
     * @Author: whh
     */
    public function customNovelForm()
    {
        $params = request()->param();
        $result = $this->validate($params, 'app\backstage\validate\SpreadValidate.customNovelForm');
        if (true !== $result) {
            $this->error($result);
        }
        $novel_id = input('novel_id');
        $type = input('type');
        $role = request()->_role;
        $user = request()->_user;
        $novel = \app\common\model\Novel::get($novel_id);
        if (!$novel) {
            $this->error('书籍不存在');
        }
        $where = [];
        $where[] = ['manager_id', '=', $user->id];
        $where[] = ['novel_id', '=', $novel_id];
        $custom = NovelCustom::where($where)->find();
        $where = [];
        $where[] = ['manager_id', '=', $user->parent_id];
        $where[] = ['novel_id', '=', $novel_id];
        $parentCustom = NovelCustom::where($where)->find();

        $this->assign('roleAlias', $role->alias);
        $this->assign('custom', $custom);
        $this->assign('parentCustom', $parentCustom);
        $this->assign('novel', $novel);
        if ($type == 2) {
            $first_pay = NovelChapter::where("novel_id", $novel_id)->where("is_pay", 1)->min('chapter_no');
            $this->assign('first_pay', $first_pay);
        }
        return $this->fetch('custom_form_' . $type);
    }

    /**
     * 自定义收费配置
     * @Author: whh
     */
    public function setCustom()
    {
        $params = request()->param();
        $result = $this->validate($params, 'app\backstage\validate\SpreadValidate.setCustom');
        if (true !== $result) {
            $this->error($result);
        }
        $key = input('key');
        $value = input('value');
        $novel_id = input('novel_id');
        $user = request()->_user;
        $where = [];
        $where[] = ['manager_id', '=', $user->id];
        $where[] = ['novel_id', '=', $novel_id];
        $item = NovelCustom::where($where)->find();
        if ($item) {
            NovelCustom::where($where)->setField($key, $value);
        } else {
            $model = new NovelCustom();
            $model->$key = $value;
            $model->novel_id = $novel_id;
            $model->manager_id = $user->id;
            $model->save();
        }
        $this->success();
    }

    /**
     * 小说详情页
     * @return mixed
     */
    public function novelInfo()
    {
        $id = input('id');
        $novel = \app\common\model\Novel::get($id);
        if (!$novel) {
            $this->error('书籍不存在');
        }
        /**
         * 查询自定义千字价格和收费章节
         */
        $role = request()->_role;
        $user = request()->_user;
        $first_pay = null;
        $words_fee = null;
        if ($role->alias == 'agent' || $role->alias == 'channel') {
            $where = [];
            $where[] = ['manager_id', '=', $user->id];
            $where[] = ['novel_id', '=', $id];
            $custom = NovelCustom::where($where)->find();
            if ($custom) {
                if ($custom->chapter_words_fee) {
                    $words_fee = $custom->chapter_words_fee;
                }
                if ($custom->chapter_first_pay) {
                    $first_pay = $custom->chapter_first_pay;
                }
            }
            if ($role->alias == 'channel' && ($first_pay === null || $words_fee === null)) {
                $where = [];
                $where[] = ['manager_id', '=', $user->parent_id];
                $where[] = ['novel_id', '=', $id];
                $parentCustom = NovelCustom::where($where)->find();
                if ($parentCustom) {
                    if ($words_fee === null) {
                        $words_fee = $parentCustom->chapter_words_fee;
                    }
                    if ($first_pay === null) {
                        $first_pay = $parentCustom->chapter_first_pay;
                    }
                }
            }
        }
        if ($words_fee === null) {
            $words_fee = $novel->words_fee;
        }
        $chapterWhere[] = ['novel_id', '=', $id];
        $chapterList = NovelChapter::where($chapterWhere)->order("chapter_no asc")->page(1, 50)->select();
        /**
         * 查询30元可阅读多少章
         */
        if ($first_pay !== null) {
            $chapterWhere[] = ['chapter_no', '>=', $first_pay];
            /**
             * 有自定义收费配置，改为收费状态
             */
            foreach ($chapterList as $k => $v) {
                if ($v['chapter_no'] >= $first_pay) {
                    $chapterList[$k]['is_pay'] = 1;
                } else {
                    $chapterList[$k]['is_pay'] = 0;
                }
            }
        } else {
            $chapterWhere[] = ['is_pay', '=', 1];
        }
        $avgWords = NovelChapter::where($chapterWhere)->avg('words');//平均章字数
        $read30Number = 0;
        if ($words_fee) {
            if (($avgWords / 1000) * $words_fee) {
                $read30Number = round(3000 / (($avgWords / 1000) * $words_fee));
            }
        }
        $this->assign('novel', $novel);
        $this->assign('words_fee', $words_fee);
        $this->assign('first_pay', $first_pay);
        $this->assign('chapterList', $chapterList);
        $this->assign('read30Number', $read30Number);
        return $this->fetch();
    }

    /**
     * 链接表单
     * @return mixed
     */
    public function linkInfoForm()
    {
        $params = request()->param();
        $result = $this->validate($params, 'app\backstage\validate\SpreadValidate.linkInfoForm');
        if (true !== $result) {
            $this->error($result);
        }

        $agent_id_gh = [53,56,68,71,75,77,79,80,88,100,101,102,103,104,105,106,107,
            108,120,122,132,133,134,135,136,137,138,139,141,142,143,258,259,260,261,262,
            263,264,265,306,330,352,683,684,685,686,687,2745,2747,2776];
        $role = request()->_role;
        $user = request()->_user;
        if($role->alias == 'agent' && in_array($user->id,$agent_id_gh))
        {
            $this->error('当前账户无法创建推广链接');
        }
        if ($role->alias == 'channel')
        {
            $parent_id = Db::table('cms_manager_user')->where('id',$user->id)->value('parent_id');
            if(in_array($parent_id,$agent_id_gh))
            {
                $this->error('当前账户无法创建推广链接');
            }
        }

        $novel_id = input('novel_id');
        $role = request()->_role;
        $user = request()->_user;
        if ($role->alias == 'channel' || $role->alias == 'agent' || $role->alias == 'eb') {
            $qas = $user->apps;
        } else {
            $qas = \app\common\model\QuickApp::getList();
        }
        $where[] = ['novel_id', '=', $novel_id];
        $where[] = ['is_pay', '=', 0];
        $chapters = NovelChapter::where($where)->select();
        $this->assign('qas', $qas);
        $this->assign('chapters', $chapters);
        //充值模版
        $temps = RechargeTemplate::where("channel_id", $user->id)->select();
        $this->assign('temps', $temps);
        return $this->fetch();
    }

    /**
     * 修改链接表单
     * @return mixed
     */
    public function editLinkInfoForm()
    {
        $id = input('id');
        $link = QuickLink::get($id);
        if (!$link) {
            $this->error('链接异常');
        }
        $role = \request()->_role;
        $user = \request()->_user;
        if ($role->alias == 'channel' && $link->channel_id != $user->id) {
            $this->error('无权限修改此链接');
        }
        if ($role->alias == 'agent' && $link->agent_id != $user->id) {
            $this->error('无权限修改此链接');
        }
        $novel = \app\common\model\Novel::where("id", $link->novel_id)->findOrFail();
        $this->assign('novel', $novel);
        $where[] = ['novel_id', '=', $link->novel_id];
        $where[] = ['is_pay', '=', 0];
        $chapters = NovelChapter::where($where)->select();
        $this->assign('chapters', $chapters);
        $qa = \app\common\model\QuickApp::where("id", $link->quick_id)->findOrFail();
        $this->assign('qa', $qa);
        $this->assign('link', $link);
        //充值模版
        $temps = RechargeTemplate::where("channel_id", $link->channel_id)->select();
        $this->assign('temps', $temps);
        return $this->fetch();
    }

    /**
     * 修改链接
     * @return mixed
     */
    public function editLink()
    {
        $params = request()->param();
        $result = $this->validate($params, 'app\backstage\validate\SpreadValidate.editLink');
        if (true !== $result) {
            $this->error($result);
        }
        $params['enter_pop'] = input('enter_pop', 0);
        return SpreadFacade::setLink($params, $params['id']);
    }

    /**
     * 隐藏链接
     * @return void
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function deleteLink()
    {
        $params = request()->param();
        $result = $this->validate($params, 'app\backstage\validate\SpreadValidate.deleteLink');
        if (true !== $result) {
            $this->error($result);
        }
        Db::table('quick_link')->where('id', $params['id'])->update(['is_delete' => 1]);
        $this->success();
    }


    /**
     * 创建链接
     * @return mixed
     */
    public function createLink()
    {
        $params = request()->param();
        $result = $this->validate($params, 'app\backstage\validate\SpreadValidate.createLink');
        if (true !== $result) {
            $this->error($result);
        }

        $agent_id_gh = [53,56,68,71,75,77,79,80,88,100,101,102,103,104,105,106,107,
                        108,120,122,132,133,134,135,136,137,138,139,141,142,143,258,259,260,261,262,
                        263,264,265,306,330,352,683,684,685,686,687,2745,2747,2776];
        $role = request()->_role;
        $user = request()->_user;
        if($role->alias == 'agent' && in_array($user->id,$agent_id_gh))
        {
            $this->error('当前账户无法创建推广链接');
        }
        if ($role->alias == 'channel')
        {
            $parent_id = Db::table('cms_manager_user')->where('id',$user->id)->value('parent_id');
            if(in_array($parent_id,$agent_id_gh))
            {
                $this->error('当前账户无法创建推广链接');
            }
        }

        $params['enter_pop'] = input('enter_pop', 0);
        return SpreadFacade::setLink($params);
    }

    /**
     * 链接页面
     * @return mixed
     */
    public function links()
    {
        $role = request()->_role;
        $user = request()->_user;
        if ($role->alias == 'channel' || $role->alias == 'agent' || $role->alias == 'eb') {
            $qas = $user->apps;
        } else {
            $qas = \app\common\model\QuickApp::getList();
        }
        $this->assign('qas', $qas);
        $this->assign('role', $role);
        return $this->fetch();
    }

    /**
     * 链接列表
     * @return \think\response\Json
     */
    public function linkList()
    {
        $token = input('token');
        $id = input('id');
        $quick_id = input('quick_id');
        $agent_id = input('agent_id');
        $channel_id = input('channel_id');
        $novel_id = input('novel_id');
        $is_delete = input('is_delete', 0);
        $page = input('page', 1);
        $limit = input('limit', 20);
        $where = [];
        if ($id != '') {
            $where[] = ['id', '=', $id];
        }

        if ($token != '') {
            $where[] = ['token', '=', $token];
        }
        if ($quick_id != '') {
            $where[] = ['quick_id', '=', $quick_id];
        }
        if ($agent_id != '') {
            $where[] = ['agent_id', '=', $agent_id];
        }
        if ($channel_id != '') {
            $where[] = ['channel_id', '=', $channel_id];
        }
        if ($novel_id != '') {
            $where[] = ['novel_id', '=', $novel_id];
        }

        if (strlen($is_delete) > 0) {
            $where[] = ['is_delete', '=', $is_delete];
        }

        $where[] = ['is_delete','<',2];

        $role = \request()->_role;
        $user = \request()->_user;

        if ($role->alias == 'channel') {
            $where[] = ['channel_id', '=', $user->id];
        }
        if ($role->alias == 'agent') {
            $where[] = ['agent_id', '=', $user->id];
        }
        if ($role->alias == 'eb') {
            $userModel = new \app\backstage\model\ManagerUser();
            $userIds = $userModel->sonUsersIds($user->id);
            $where[] = ['agent_id', 'in', $userIds];
            $where[] = ['agent_id', '<>', 0];
        }


        $logic = new SpreadLogic();
        $list = $logic->linkList($where, $page, $limit);
        $count = QuickLink::getCount($where);
        return sucJson($list, $count);
    }

    /**
     * 修改链接状态
     */
    public function changeLinkStatus()
    {
        $params = request()->param();
        $result = $this->validate($params, 'app\backstage\validate\SpreadValidate.changeLinkStatus');
        if (true !== $result) {
            $this->error($result);
        }
        $link = QuickLink::get($params['id']);
        if (!$link) {
            $this->error('链接异常');
        }
        $role = \request()->_role;
        $user = \request()->_user;
        if ($role->alias == 'channel' && $link->channel_id != $user->id) {
            $this->error('无权限修改此链接');
        }
        if ($role->alias == 'agent' && $link->agent_id != $user->id) {
            $this->error('无权限修改此链接');
        }
        if ($params['field'] == 'status') {
            $link->status = $params['value'];
        } else {
            $link->allow_register = $params['value'];
        }
        $link->save();
        $this->success();
    }

    /**
     * 修改链接成本
     */
    public function changeCost()
    {
        $params = request()->param();
        $result = $this->validate($params, 'app\backstage\validate\SpreadValidate.changeCost');
        if (true !== $result) {
            $this->error($result);
        }
        $link = QuickLink::get($params['id']);
        if (!$link) {
            $this->error('链接异常');
        }
        $role = \request()->_role;
        $user = \request()->_user;
        if ($role->alias == 'channel' && $link->channel_id != $user->id) {
            $this->error('无权限修改此链接');
        }
        if ($role->alias == 'agent' && $link->agent_id != $user->id) {
            $this->error('无权限修改此链接');
        }
        $cost = input('cost');
        $link->cost = $cost;
        $link->save();
        $this->success();
    }

    /**
     * 链接明细
     * @return mixed
     */
    public function linkDaily()
    {
        $id = input('id');
        $link = Link::get($id);
        if (!$link) {
            $this->error('链接不存在');
        }
        $logic = new SpreadLogic();
        $yesterday = date("Y-m-d", strtotime("-1 day"));
        if (request()->isAjax()) {
            $page = input('page', 1);
            $limit = input('limit', 10);
            $date = input('date');
            $where[] = ['link_id', '=', $id];
            if ($date != ''){
                $where[] = ['report_date', '=', $date];
            }
            $where[] = ['report_date', '<', $yesterday];
            return $logic->linkDaily($where, $page, $limit);
        }else{
            $todayData = $logic->linkDateData($id, date("Y-m-d"));
            $yesterdayData = $logic->linkDateData($id, $yesterday);
            $this->assign('todayData', $todayData);
            $this->assign('yesterdayData', $yesterdayData);
            $this->assign('id', $id);
            $link = Link::get($id);
            $this->assign('id', $id);
            $this->assign('link', $link);
            return $this->fetch();
        }
    }
}